{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# This notebook has been tested with Python 3.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "import concurrent.futures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Download URL from ImageNet as a text file in advanced"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "urlList = []\n",
    "# Open a url text file: './man_sport.txt'\n",
    "filename = 'man_sport.txt'\n",
    "# Read file\n",
    "with open(filename) as f:\n",
    "    for line in f:\n",
    "        urlList += [line]    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Crawl images and save\n",
    "# Path is the target directory to save images\n",
    "def loadImage(url, path):\n",
    "    res = requests.get(url)\n",
    "    if res.status_code == 200:\n",
    "        path = path + url.split('/')[-1].split('\\n')[0]\n",
    "        with open(path, 'wb') as f:\n",
    "            f.write(res.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Multi-thread to speed up \n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:\n",
    "    for url in urlList:\n",
    "        try:\n",
    "            executor.submit(loadImage, url, 'male/')\n",
    "        except Exception as exc:\n",
    "            print(exc)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
